<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="getTitle" width="650px" @ok="handleSubmit" destroyOnClose>
    <BasicForm @register="registerForm">
      <template #fileSizeLimit="{ model, field }">
        <a-input v-model:value="model[field]" placeholder="请输入限制大小" suffix="KB" />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, useAttrs, reactive } from "vue"
  import { BasicForm, useForm } from "/@/components/Form"
  import { BasicDrawer, useDrawerInner } from "/@/components/Drawer"
  import { formSchema } from "./data"
  import * as apis from "/@/api/infra/file"
  import { useMessage } from "/@/hooks/web/useMessage"
  const { createMessage } = useMessage()

  const emit = defineEmits(["success", "register"])
  const attrs = useAttrs()
  const isUpdate = ref(true)
  const [registerForm, { setProps, resetFields, setFieldsValue, validate }] = useForm({
    wrapperCol: {
      md: { span: 20 },
      sm: { span: 20 },
    },

    labelWidth: 100,
    schemas: formSchema,
    showActionButtonGroup: false,
  })
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    resetFields()
    isUpdate.value = !!data?.isUpdate
    setDrawerProps({ confirmLoading: false })
    if (isUpdate.value) {
      data.record = await apis.getFileConfig({ id: data.record.id })
    }
    let fileTypeLimit = []
    if (data.record.fileTypeLimit) {
      fileTypeLimit = data.record.fileTypeLimit.split(",")
    }
    if (unref(isUpdate)) {
      setFieldsValue({
        ...data.record,
        fileTypeLimit,
      })
    }
    setProps({ disabled: !attrs.showFooter })
  })

  const getTitle = computed(() => (!unref(isUpdate) ? "新增文件配置" : "编辑文件配置"))

  async function handleSubmit() {
    try {
      const values = await validate()
      setDrawerProps({ confirmLoading: true })

      const form: any = { ...values }
      console.log("domainTarget: ", form)

      await apis.saveOrUpdateFileConfig(form, isUpdate.value)
      closeDrawer()
      emit("success")
      createMessage.success(`${getTitle.value}成功`)
    } finally {
      setDrawerProps({ confirmLoading: false })
    }
  }
</script>
